/**
 * 微信配置
  */

import wx from 'weixin-js-sdk';
import API from 'src/api/wx';

export default {
    debug: process.env.NODE_ENV === 'development',
    // debug: true,
    baseApiList: ['checkJsApi', 'onMenuShareTimeline',
        'onMenuShareAppMessage', 'onMenuShareQQ',
        'onMenuShareWeibo', 'onMenuShareQZone',
        'hideMenuItems', 'showMenuItems',
        'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem',
        'translateVoice', 'startRecord', 'stopRecord',
        'onVoiceRecordEnd', 'playVoice', 'onVoicePlayEnd',
        'pauseVoice', 'stopVoice', 'uploadVoice',
        'downloadVoice', 'chooseImage', 'previewImage',
        'uploadImage', 'downloadImage', 'getNetworkType',
        'openLocation', 'getLocation', 'hideOptionMenu',
        'showOptionMenu', 'closeWindow', 'scanQRCode',
        'chooseWXPay', 'openProductSpecificView', 'addCard',
        'chooseCard', 'openCard', 'updateAppMessageShareData', 'updateTimelineShareData'],
    wx,
    // 初始化
    init() {
        return new Promise((resolve, reject) => {
            API.getJsConfig({
                url: encodeURIComponent(location.href.split('#')[0])
            })
                .then(res => {
                    // wx配置
                    wx.config({
                        debug: this.debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: res.appId, // 必填，公众号的唯一标识
                        timestamp: res.timestamp, // 必填，生成签名的时间戳
                        nonceStr: res.nonceStr, // 必填，生成签名的随机串
                        signature: res.signature, // 必填，签名
                        jsApiList: res.apiList || this.baseApiList // 必填，需要使用的JS接口列表
                    });

                    wx.ready(() => {
                        resolve(wx);
                    });
                    // 验证失败
                    wx.error((err) => {
                        reject(err);
                    });
                })
                .catch(err => {
                    reject(err);
                });
        });
    },
    // 检测是否支持js接口
    checkJsApi(apisName) {
        return new Promise((resolve, reject) => {
            wx.checkJsApi({
                jsApiList: [...apisName],
                success(res) {
                    resolve(res);
                },
                fail(err) {
                    reject(err);
                }
            });
        });
    }
};
